Skip to content

Conversation

@tet4enko
Copy link
Owner

No description provided.

String rounded = String.format("%.2f", price).replace(',', '.');

// передаем уже округленное значение для гарантии консистентности
return String.format("%s %s", rounded, getPriceSpelling(Float.parseFloat(rounded)));
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

благодаря этому финту, если мы в эту функцию передадим 1.9999, то на выходе будет строка "2.00 рубля", а не "2.00 рубль"

Comment on lines 2 to 3
final static private int MIN_PEOPLE_COUNT = 2;
final static private String FINISH_COMMAND = "Завершить";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Модификаторы класса и полей, если они присутствуют, отображаются в порядке, рекомендованном спецификацией языка Java:
public protected private abstract default static final transient volatile synchronized native strictfp

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То есть здесь привычнее было бы видеть
private static final

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

спасибо, не знал =)

Comment on lines +10 to +13
String.format(
"На скольких человек разделить счет ? (значение должно быть >=%d)",
MIN_PEOPLE_COUNT
)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Круто, что ты везде по максимуму используешь форматирование строк через String.format, т.к. это работает быстрее и требует меньше памяти, чем та же конкатенация строк. Есть ещё класс StringBuilder, который работает ещё быстрее чем String.format, можешь почитать о нём, а может и применишь и в этой практической работе

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

спасибо, почитаю


calculator.add(product);

String command = TerminalReader.readString("Хотите добавить еще товар ?");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сейчас немного неочевидно для обычного пользователя, что нужно ввести "завершить", чтобы не вводить товар, я бы в это сообщение дописал об этом

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

справедливо


public class TerminalReader {
final static private Scanner scanner = new Scanner(System.in);
public static String readString(String message) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эта функция имеет модификатор public, а другие две функции ниже - нет, хотя логично было бы предположить, что эти три функции должны иметь один и тот же модификатор доступа (public)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по-умолчанию проде они public и так идут, да ?

есть ли смысл явно прописывать ?

Copy link

@ArturNurtdinov ArturNurtdinov Feb 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По умолчанию в джаве они package-private, то есть видимость на уровне пакета
В Котлине по умолчанию публичные, но есть случаи (например когда пишешь библиотеку) когда нужно прописывать явно

} catch (NumberFormatException e) {
System.out.printf("\"%s\" не является числом%n", stringValue);

return readInt(message);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Рекурсия обычно не совсем подходит для решения задач из-за затрат по памяти и скорости работы (она проигрывает циклам), поэтому здесь лучше воспользоваться плоским циклом while (true), чтобы избежать использования рекурсии

@tet4enko
Copy link
Owner Author

@ArturNurtdinov все поправил, и добавил валидацию цены на отрицательное значение

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants